﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.MVC;
using System.Web.Security;
using AutoMapper;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using NTQOnlineExam.Services.CommandService.Account;
using NTQOnlineExam.Services.DBCommand.Account;
using NTQOnlineExam.Services.Models;
using NTQOnlineExam.Services.ReportService.Account;
using WebMatrix.WebData;
using NTQOnlineExamFrontend.Filters;
using NTQOnlineExamFrontend.Models;

namespace NTQOnlineExamFrontend.Controllers
{
    [Authorize]
    public class AccountController : Controller
    {
        private readonly IAccountCommandService _accountCommandService;
        private readonly IAccountReportService _accountReportService;
        public AccountController(IAccountCommandService accountCommandService, IAccountReportService accountReportService)
        {
            _accountCommandService = accountCommandService;
            _accountReportService = accountReportService;
        }

        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            if (!string.IsNullOrEmpty(returnUrl) && returnUrl.ToLower().Contains("logoff"))
                returnUrl = string.Empty;

            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            try
            {
                if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
                {
                    return RedirectToLocal(returnUrl);
                }
            }
            catch (Exception)
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
                // If we got this far, something failed, redisplay form
            }
            return View(model);
        }

        [AllowAnonymous]
        public ActionResult ForgotPassword()
        {
            return View(new ForgotPasswordModel());
        }

        [HttpPost]
        [AllowAnonymous]
        public ActionResult ForgotPassword(ForgotPasswordModel model)
        {
            if (!ModelState.IsValid)
            {
                return ModelState.JsonValidation();
            }
            try
            {
                _accountCommandService.ResetPassword(new ResetPasswordCommand() { Email = model.Email, RandomString = GenerateChar() });
                return ModelState.JsonValidation(new { Success = true });
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("ForgotPassword", ex.Message);
            }
            return ModelState.JsonValidation();
        }

        [AllowAnonymous]
        [HttpGet]
        public ActionResult ResetPassword(string token)
        {
            try
            {
                var command = new ApplyResetPasswordCommand(token);
                _accountCommandService.ApplyResetPasswordToUser(command);
                return Redirect(Url.RouteUrl(new { Controller = "Term", Action = "GetTerms" }));
            }
            catch (Exception ex)
            {
                return View(new ResetPasswordModel() { Message = ex.Message });
            }
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            WebSecurity.Logout();

            return RedirectToAction("Login", "Account");
        }

        [AllowAnonymous]
        public ActionResult Register()
        {
            return View(new RegisterModel());
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    _accountCommandService.CreateUserWithAccount(new CreateUserAccountCommand()
                                                                    {
                                                                        Username = model.UserName,
                                                                        Password = model.Password,
                                                                        Roles = new List<string>() { RoleList.Customer.ToString() },
                                                                        FirstName = model.FirstName,
                                                                        LastName = model.LastName,
                                                                        Email = model.Email,
                                                                        PhoneNumber = model.Phone,
                                                                        BillingAddress = model.Address,
                                                                        BillingCity = model.City,
                                                                        BillingZipCode = model.ZipCode,
                                                                        BillingPOBox = model.POBox,
                                                                        BillingCountry = model.Country
                                                                    }
                                                                );
                    WebSecurity.Login(model.UserName, model.Password);
                    return RedirectToAction("GetTerms", "Term");
                }
                catch (Exception e)
                {
                    ModelState.AddModelError("", e.Message);
                }
            }
            return View(model);
        }

        public ActionResult Manage(ManageMessageId? message)
        {
            ViewBag.ResultMessage =
                message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
                : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
                : message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
                : "";
            ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            ViewBag.ReturnUrl = Url.Action("Manage");

            IList<BreadcrumItem> breadcrumItems = new List<BreadcrumItem>();
            breadcrumItems.Add(new BreadcrumItem("Personal", "/Order/OrderHistory", false));
            breadcrumItems.Add(new BreadcrumItem("Change password", string.Empty, true));
            ViewData["Breadcrumb"] = breadcrumItems;

            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Manage(LocalPasswordModel model)
        {
            bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            ViewBag.HasLocalPassword = hasLocalAccount;
            ViewBag.ReturnUrl = Url.Action("Manage");
            if (hasLocalAccount)
            {
                if (ModelState.IsValid)
                {
                    // ChangePassword will throw an exception rather than return false in certain failure scenarios.
                    bool changePasswordSucceeded;
                    try
                    {
                        changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
                    }
                    catch (Exception)
                    {
                        changePasswordSucceeded = false;
                    }

                    if (changePasswordSucceeded)
                    {
                       // return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
                        ViewBag.ResultMessage = "Your password has been changed successfully.";
                    }
                    else
                    {
                        ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                    }
                }
            }
            else
            {
                // User does not have a local password so remove any validation errors caused by a missing
                // OldPassword field
                ModelState state = ModelState["OldPassword"];
                if (state != null)
                {
                    state.Errors.Clear();
                }

                if (ModelState.IsValid)
                {
                    try
                    {
                        WebSecurity.CreateAccount(User.Identity.Name, model.NewPassword);
                        return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
                    }
                    catch (Exception)
                    {
                        ModelState.AddModelError("", String.Format("Unable to create local account. An account with the name \"{0}\" may already exist.", User.Identity.Name));
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        public ActionResult Profile()
        {
            IList<BreadcrumItem> breadcrumItems = new List<BreadcrumItem>();
            breadcrumItems.Add(new BreadcrumItem("Personal", "/Order/OrderHistory", false));
            breadcrumItems.Add(new BreadcrumItem("Your profile", string.Empty, true));
            ViewData["Breadcrumb"] = breadcrumItems;

            var user = _accountReportService.GetCurrentUser();
            if (user == null) return new EmptyResult();
            var itemDto = _accountReportService.GetByUserId((int)user.ProviderUserKey);
            var model = Mapper.Map<UserProfileDTO, ProfileViewModel>(itemDto);
            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Profile(ProfileViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var user = _accountReportService.GetCurrentUser();
                    if (user == null) throw new InvalidDataException("Can't find profile for current user");
                    _accountCommandService.UpdateUser(new UpdateUserCommand()
                    {
                        UserId = model.UserId,
                        FirstName = model.FirstName,
                        LastName = model.LastName,
                        Email = model.Email,
                        PhoneNumber = model.Phone,
                        BillingAddress = model.BillingAddress,
                        BillingCity = model.BillingCity,
                        BillingCountry = model.BillingCountry,
                        BillingPOBox = model.BillingPOBox,
                        BillingZipCode = model.BillingZipCode,
                        Username = model.UserName
                    });
                    ViewBag.ResultMessage = "Update profile successfully!";
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.Message);
                }

            }


            return View(model);
        }

        #region Helpers
        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("GetTerms", "Term");
            }
        }

        public enum ManageMessageId
        {
            ChangePasswordSuccess,
            SetPasswordSuccess,
            RemoveLoginSuccess,
        }

        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }

        private string GenerateChar()
        {
            var random = new Random();
            return Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))).ToString();
        }
        #endregion
    }
}
